/**
 * @(#)CodeEntitySimpleAssociationRelation.java, 2008-4-30.
 * Copyright 2008  Program Analysis Research Group(PARG),Institute of Software, Peking University.
 * All rights reserved.
 */
package edu.pku.sei.pgie.analyzer.internal.relation;

import java.util.ArrayList;
import java.util.List;

import org.eclipse.jdt.core.dom.CompilationUnit;
import org.eclipse.jdt.core.dom.FieldDeclaration;
import org.eclipse.jdt.core.dom.Type;

import edu.pku.sei.pgie.analyzer.internal.CodeEntitySymbolTable;
import edu.pku.sei.pgie.analyzer.internal.VisitorWithContext;
import edu.pku.sei.pgie.analyzer.util.TypeAnalyzer;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/**
 * @author HeLi
 */
public class CodeEntitySimpleAssociationRelation extends
        AbstractCodeEntityRelation {
    private static Log logger = LogFactory
            .getLog(CodeEntitySimpleAssociationRelation.class);

    private TypeAnalyzer typeAnalyzer;

    public CodeEntitySimpleAssociationRelation() {
        typeAnalyzer = new TypeAnalyzer();
    }

    public class SimpleAssociationVisitor extends VisitorWithContext {
        List<String[]> container;

        public SimpleAssociationVisitor() {
            super(true);
            this.container = new ArrayList<String[]>();
        }

        @SuppressWarnings("unchecked")
        public boolean visit(FieldDeclaration node) {
            Type fieldType = node.getType();
            TypeAnalyzer.TypeInfo fieldTypeInfo = typeAnalyzer.analyze(fieldType);
            String fieldTypeName = fieldTypeInfo.typeName;
            String[] componentTypes = null;
            if(fieldTypeInfo.isContainer()) {
                 componentTypes = fieldTypeInfo.getContainerElementTypes();
            }
            if (fieldTypeName != null) {
                container.add(new String[] {
                    peekTypeFQN(), fieldTypeName
                });
                if(componentTypes != null) {
                    for(String componentType : componentTypes) {
                        container.add(new String[]{
                           peekTypeFQN(),componentType
                        });
                    }
                }
            }
            return true;
        }

        public List<String[]> getResult() {
            return container;
        }
    }

    public String[][] collectCallBack(CompilationUnit root,
            CodeEntitySymbolTable symbolTable) throws Exception {
        SimpleAssociationVisitor visitor = new SimpleAssociationVisitor();
        root.accept(visitor);
        List<String[]> result = visitor.getResult();
        /*if(result.size() == 0) {
        	logger.debug("simple association result is zero");
        } else {
        	logger.debug("simple association result size="+result.size());
        }*/
        return result.toArray(new String[result.size()][]);
    }

}
